#include "StdAfx.h"
#include "BuildEventHandler.h"

BuildEventHandler::BuildEventHandler(void)
{
}

BuildEventHandler::~BuildEventHandler(void)
{
	UnAdvise();
}

BOOL BuildEventHandler::Advise(EnvDTE80::DTE2 *pDTE, IBuildEventHandler *pReceiver)
{
	UnAdvise();

	BOOL bRet = FALSE;
	if ((pDTE) && (pReceiver))
	{
		m_pReceiver = pReceiver;

		EnvDTE::EventsPtr spEvents;
		EnvDTE::_BuildEventsPtr sp_BuildEvents;
		IConnectionPointContainerPtr spCon;

		if (SUCCEEDED(pDTE->get_Events(&spEvents)) &&
			SUCCEEDED(spEvents->get_BuildEvents(&sp_BuildEvents)) &&
			(spCon = sp_BuildEvents) &&
			SUCCEEDED(spCon->FindConnectionPoint(EnvDTE::DIID__dispBuildEvents, &m_spCP)) &&
			SUCCEEDED(m_spCP->Advise(this, &m_dwCookie)))
		{
			bRet = TRUE;
		}
		
	}

	return bRet;
}

void BuildEventHandler::UnAdvise()
{
	if (m_spCP)
	{
		m_spCP->Unadvise(m_dwCookie);
		m_spCP = NULL;
	}
	m_pReceiver = NULL;
}

HRESULT STDMETHODCALLTYPE BuildEventHandler::QueryInterface(REFIID riid, void** ppvObject)
{
	if (ppvObject == NULL)
		return E_POINTER;

	if ((riid == IID_IUnknown) ||
		(riid == IID_IDispatch) ||
		(riid == EnvDTE::DIID__dispBuildEvents))
	{
		*ppvObject = this;
		//AddRef();
		return S_OK;
	}

	return E_NOINTERFACE;
}

ULONG STDMETHODCALLTYPE BuildEventHandler::AddRef(void)
{
	return 1;
}

ULONG STDMETHODCALLTYPE BuildEventHandler::Release(void)
{
	return 1;
}

HRESULT STDMETHODCALLTYPE BuildEventHandler::GetTypeInfoCount(UINT *pctinfo)
{
	return E_NOTIMPL;
}

HRESULT STDMETHODCALLTYPE BuildEventHandler::GetTypeInfo(UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo)
{
	return E_NOTIMPL;
}

HRESULT STDMETHODCALLTYPE BuildEventHandler::GetIDsOfNames(REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId)
{
	return E_NOTIMPL;
}

HRESULT STDMETHODCALLTYPE BuildEventHandler::Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
	switch(dispIdMember)
	{
	case 3: //OnBuildBegin
		m_pReceiver->OnBuildBegin(
			(EnvDTE::vsBuildScope)pDispParams->rgvarg[1].lVal,
			(EnvDTE::vsBuildAction)pDispParams->rgvarg[0].lVal);
		break;
	case 4: //OnBuildDone
		m_pReceiver->OnBuildDone(
			(EnvDTE::vsBuildScope)pDispParams->rgvarg[1].lVal,
			(EnvDTE::vsBuildAction)pDispParams->rgvarg[0].lVal);
		break;
	case 5: //OnBuildProjConfigBegin
		m_pReceiver->OnBuildProjConfigBegin(
			pDispParams->rgvarg[3].bstrVal,
			pDispParams->rgvarg[2].bstrVal,
			pDispParams->rgvarg[1].bstrVal,
			pDispParams->rgvarg[0].bstrVal);

		break;
	case 6: //OnBuildProjConfigDone
		m_pReceiver->OnBuildProjConfigDone(
			pDispParams->rgvarg[4].bstrVal,
			pDispParams->rgvarg[3].bstrVal,
			pDispParams->rgvarg[2].bstrVal,
			pDispParams->rgvarg[1].bstrVal,
			pDispParams->rgvarg[0].boolVal
			);
		break;
	}
	return S_OK;
}
